package com.example.tools.security.interceptor;

import cn.hutool.json.JSONUtil;
import com.example.mallcommon.RestResult;
import com.example.mallcommon.constant.AuthConstant;
import com.example.mallcommon.constant.ResultCodeEnum;
import com.example.mallcommon.utils.WebUtils;
import com.example.tools.security.properties.MallSecurityProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description:
 * 编写拦截器，用于校验请求是否经过网关
 * @author Yang
 * create time 2021-08-25 0:33
 * @since 0.0.1
 */
public class ServerProtectInterceptor implements HandlerInterceptor {

    private MallSecurityProperties properties;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler){

        if (!properties.getOnlyFetchByGateway()) {
            return true;
        }

        String token = request.getHeader(AuthConstant.GATEWAY_TOKEN_HEADER);

        String gatewayToken = new String(Base64Utils.encode(AuthConstant.GATEWAY_TOKEN_VALUE.getBytes()));

        if (StringUtils.equals(gatewayToken, token)) {
            return true;
        } else {
             String resBody = JSONUtil.toJsonStr(RestResult.failed(ResultCodeEnum.USER_ACCESS_VIST_GATEWAY));
            WebUtils.writeJson(response,resBody);
            return false;
        }
    }

    public void setProperties(MallSecurityProperties properties) {
        this.properties = properties;
    }
}